package com.sdp.core.bizc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.threadLocal.ContextManager;
import com.sdp.core.bizc.utils.CoreConstantsEnum;
import com.sdp.core.bizc.utils.TokenUtils;


public class SystemInterceptor implements HandlerInterceptor{

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
		try {
			String systemNo = request.getHeader(CoreConstantsEnum.header中的模块参数名.getCode());
			String token = request.getHeader(CoreConstantsEnum.header中的token参数名.getCode());
			if(StringUtils.isEmpty(systemNo) || StringUtils.isEmpty(token)) {
				return false;
			}
			JSONObject obj = TokenUtils.verify(token);
			if(obj==null) {
				return false;
			}
			if(StringUtils.isEmpty(obj.get(CoreConstantsEnum.token中账号的属性名.getCode())) 
					|| StringUtils.isEmpty(obj.get(CoreConstantsEnum.token中工号的属性名.getCode()))
					|| StringUtils.isEmpty(obj.get(CoreConstantsEnum.token中密码的属性名.getCode()))
					|| StringUtils.isEmpty(obj.get(CoreConstantsEnum.token中姓名的属性名.getCode()))) {
				return false;
			}
			ContextManager.setContextData(CoreConstantsEnum.header中的模块参数名.getCode(), systemNo);
			ContextManager.setContextData(CoreConstantsEnum.token中账号的属性名.getCode(),obj.getString(CoreConstantsEnum.token中账号的属性名.getCode()));
			ContextManager.setContextData(CoreConstantsEnum.token中工号的属性名.getCode(),obj.getString(CoreConstantsEnum.token中工号的属性名.getCode()));
			ContextManager.setContextData(CoreConstantsEnum.token中姓名的属性名.getCode(),obj.getString(CoreConstantsEnum.token中姓名的属性名.getCode()));
			
			
			return true;	
		} catch (Exception e) {

			return false;
		}
	}

	/**
	 * 请求处理之后进行调用（Controller方法调用之后）
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv)
			throws Exception {

	}

	/**
	 * 在整个请求结束之后被调用（主要是用于进行资源清理工作） 一定要在请求结束后调用remove清除当前线程的副本变量值，否则会造成内存泄漏
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex)
			throws Exception {
		
		ContextManager.clearContextData();
	}
}
